package controllers

import (
	"encoding/json"
	"ssims/models"
	"ssims/pkg/app"
	"ssims/pkg/e"
	"ssims/services"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func GetRelation(c *gin.Context) {
	page := -1
	if arg := c.Query("page"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	limit := -1
	if arg := c.Query("limit"); arg != "" {
		limit = com.StrTo(arg).MustInt()
	}
	searchId := ""
	if arg := c.Query("searchId"); arg != "" {
		searchId = arg
	}
	supplierParam := map[string]interface{}{
		"page":     page,
		"limit":    limit,
		"searchId": searchId,
	}
	err, info, total := services.GetAllRelation(supplierParam)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "查询成功")
}

func DelRelation(c *gin.Context) {
	id := ""
	if arg := c.Query("family_id1"); arg != "" {
		id = arg
	}
	if id == "" {
		app.INFO(c, 30001, "参数错误")
		return
	}
	err := services.DelRelation(id)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "删除成功")
}

func UpdateRelation(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	if m["FamilyId1"] == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	family_id1 := m["FamilyId1"]
	id1_name := m["Id1Name"]
	family_id2 := m["FamilyId2"]
	id2_name := m["Id2Name"]
	relation_type := m["RelationType"]

	err := services.UpdateRelation(models.Relation{
		FamilyId1:    family_id1,
		Id1Name:      id1_name,
		FamilyId2:    family_id2,
		Id2Name:      id2_name,
		RelationType: relation_type,

		Isdel: false})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "更新成功")
}

func AddRelation(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	family_id1 := m["FamilyId1"]
	id1_name := m["Id1Name"]
	family_id2 := m["FamilyId2"]
	id2_name := m["Id2Name"]
	relation_type := m["RelationType"]

	err := services.AddRelation(models.Relation{
		FamilyId1:    family_id1,
		Id1Name:      id1_name,
		FamilyId2:    family_id2,
		Id2Name:      id2_name,
		RelationType: relation_type,

		Isdel: false})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "添加成功")
}
